package com.ailanyin.security.handle;

import com.ailanyin.security.service.SecurityUserService;
import com.ailanyin.security.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出处理类
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022/1/4 0004 下午 16:20
 */
@Component
public class LogoutHandler implements LogoutSuccessHandler {

    @Autowired
    private SecurityUserService securityUserService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());
            String username = TokenUtil.getUserNameFromToken(authToken);
            securityUserService.delUserDetailsFromCache(username);
        }
    }
}
